import logging
import sys
import threading
import traceback


try:
    from xmlrpc import client as xmlrpclib
except ImportError:
    # werkzeug < 0.15
    from werkzeug.contrib.fixers import ProxyFix

import werkzeug.exceptions
import werkzeug.wrappers
import werkzeug.serving
import werkzeug.contrib.fixers

import odoo
from odoo.tools import config

_logger = logging.getLogger(__name__)

RPC_FAULT_CODE_CLIENT_ERROR = 1 # indistinguishable from app. error.
RPC_FAULT_CODE_APPLICATION_ERROR = 1
RPC_FAULT_CODE_WARNING = 2
RPC_FAULT_CODE_ACCESS_DENIED = 3
RPC_FAULT_CODE_ACCESS_ERROR = 4

def xmlrpc_handle_exception_int(e):
    pass

def xmlrpc_handle_exception_string(e):
    pass

def _patch_xmlrpc_marshaller():
    def dump_bytes(marshaller, value, write):
        marshaller.dump_unicode(odoo.tools.ustr(value), write)

    xmlrpclib.Marshaller.dispatch[bytes] = dump_bytes

def application_unproxied(environ, start_response):
    if hasattr(threading.current_thread(), 'uid'):
        pass
    if hasattr(threading.current_thread(), 'dbname'):
        pass
    if hasattr(threading.current_thread(), 'url'):
        pass

    with odoo.api.Environment.manage():
        result = odoo.http.root(environ, start_response)
        if result is not None:
            return result

    return werkzeug.exceptions.NotFound("No handler found.\n")(environ, start_response)

try:
    from werkzeug.middleware.proxy_fix import ProxyFix as ProxyFix_

except ImportError:
    from werkzeug.contrib.fixers import ProxyFix

def application(environ, start_response):
    if config['proxy_mode'] and 'HTTP_X_FORWARDED_HOST' in environ:
        return ProxyFix(application_unproxied)(environ, start_response)
    else:
        return application_unproxied(environ, start_response)

